#!/usr/bin/env python
# vim:ts=4:sw=4:noet:

import os
import markdown
import sys
import glob

outdir = "."

def genFile(basepath, ifn, title, cssfile, next="", prev=""):
	ofn = basepath+outdir+"/"+ifn.split(".")[0]+".html"
	idata = file(basepath+ifn, "rt").read()
	hdata = file(basepath+"header.html","rt").read()
	fdata = file(basepath+"footer.html","rt").read()
	ohtml = markdown.markdown(idata)

	of = file(ofn,"wt")
	of.write(hdata % (title, cssfile))
	of.write(ohtml)
	of.write(fdata % (prev, next))
	of.close()

def genIndex(basepath, fns):
	ofn = basepath+outdir+"/tutorial.html"
	hdata = file(basepath+"header.html","rt").read()
	fdata = file(basepath+"footer.html","rt").read()

	of = file(ofn,"wt")
	of.write(hdata % ("Foxtalk Tutorial", "tutorial.css"))
	of.write("<h1>Foxtalk Tutorial</h1>")
	of.write("<h2>Tutorial Index</h2>")
	of.write("<ul>")
	for fn in fns:
		sfn = fn.split(".")[0].split("_")
		if sfn[0]!="tut":
			pass
		num = int(sfn[1])
		name = " ".join(sfn[2:])
		link = fn.replace(".txt",".html")
		#name = fn
		of.write("<li><a href=\"%s\">%s</a></li>" % (link, name))
	of.write("</ul>")
	next = "<a class=\"alnright\" href=\"%s\">Next</a>" % (
			fns[0].replace("txt","html"))
	of.write(fdata % ("",next))
	of.close()

def genTutorial(basepath):
	files = sorted([os.path.split(f)[-1] for f in glob.glob(basepath+"tut_*.txt")])
	genIndex(basepath, files)
	for i, fn in enumerate(files):
		sfn = fn.split(".")[0].split("_")
		if sfn[0]!="tut":
			pass
		num = int(sfn[1])
		name = " ".join(sfn[2:])
		title = "Foxtalk Tutorial - %d - %s" % (num, name)
		cssfile = "tutorial.css"
		#print title
		next = prev = ""
		if i<(len(files)-1):
			next = "<a class=\"alnright\" href=\"%s\">Next</a>" % (
					files[i+1].replace("txt","html"))
		if (i>0):
			prev = "<a class=\"alnleft\" href=\"%s\">Previous</a>" % (
					files[i-1].replace("txt","html"))
		else:
			prev = "<a class=\"alnleft\" href=\"tutorial.html\">Previous</a>"
		genFile(basepath, fn, title, cssfile, next, prev)

def genReference(basepath):
	files = {
		"syntax.txt" : "Foxtalk Reference",
		"reference.txt" : "Foxtalk Reference",
	}
	for f in files:
		genFile(basepath, f, files[f], "tutorial.css")

def main(args):
	basepath = os.path.split(args[0])[0]+"/"
	genTutorial(basepath)
	genReference(basepath)

if __name__=="__main__":
	main(sys.argv)
